package com.itheima.tlias08_14.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias08_14.VO.PageVO;
import com.itheima.tlias08_14.dto.PageClazzDTO;
import com.itheima.tlias08_14.dto.SelectByIdClazzDTO;
import com.itheima.tlias08_14.dto.SelectDataTimeClazzDTO;
import com.itheima.tlias08_14.entity.Clazz;
import com.itheima.tlias08_14.mapper.ClazzMapper;
import com.itheima.tlias08_14.mapper.StudentMapper;
import com.itheima.tlias08_14.paramobject.InsertClazz;
import com.itheima.tlias08_14.paramobject.SelectClazz;
import com.itheima.tlias08_14.service.ClazzService;
import com.itheima.tlias08_14.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class  ClazzServiceImp implements ClazzService {
    @Resource
    ClazzMapper mapper;
    @Override
    public ResultUtil selectClazz(SelectClazz selectClazz) {
        int i = mapper.updateClazzStatus();
        Page<Object> page = PageHelper.startPage(selectClazz.getPage(), selectClazz.getPageSize());
        List<PageClazzDTO> selectDataTimeClazzDTOS = mapper.selectClazz(selectClazz);
        System.out.println("获取到的数据为：");
        selectDataTimeClazzDTOS.forEach(e->System.out.println(e));
        PageVO<PageClazzDTO> pageVO = new PageVO<>();
        //pageVO.setTotal(page.getTotal());
        pageVO.setTotal(page.getTotal());
        pageVO.setRows(selectDataTimeClazzDTOS);
        return ResultUtil.success(pageVO);
    }


    @Resource
    StudentMapper studentMapper;
    @Override
    //启动事务  识别是否出现异常，如果出现异常，回滚事务
    //事务在私有方法中 回滚会失效
    //事务在tray catch 中 回滚失效
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil deleteClazzById(Integer id) {
        //删除班级前先判断班级是否是处于已经结课状态
        if (mapper.selectClazzById(id).getEndDate().isBefore(LocalDate.now())) {
            //删除该班级对应的学生
            studentMapper.hatchDeleteByClazzId(id);
            int i = mapper.deleteClazzById(id);
            return ResultUtil.success();
        }
        return ResultUtil.failure("班级处于未结课状态！");

    }

    @Override
    public int insertClazz(InsertClazz insertClazz) {
        int i = mapper.insertClazz(insertClazz);
        return i;
    }

    @Override
    public SelectByIdClazzDTO selectClazzById(Integer id) {
        SelectByIdClazzDTO selectByIdClazzDTO = mapper.selectClazzById(id);
        return selectByIdClazzDTO;
    }

    @Override
    public int updateClazz(Clazz clazz) {
        int i = mapper.updateClazz(clazz);
        return i;
    }

    @Override
    public List<SelectDataTimeClazzDTO> selectAllClazz() {
        List<SelectDataTimeClazzDTO> selectAllClazz = mapper.selectAllClazz();
        return selectAllClazz;
    }
}
